import 'package:get/get.dart';
import 'package:mall/modules/service/cart_service.dart';
import 'package:mall/utils/broadcast/broadcast_util.dart';
import 'package:mall/utils/sc/state_controller.dart';

import '../model/cart_entity.dart';

class CartSc extends ModelSC<CartEntity> implements CartEvent {

  RxBool isAllCheck = false.obs;

  @override
  void onInit() {
    super.onInit();
    BroadcastUtil.register<CartEvent>(this);

    ever(data, (value) {
      final list = value?.cartList ?? [];
      var isAllCheck = true;
      for (var element in list) {
        if (element.checked == null || !element.checked!) {
          isAllCheck = false;
          break;
        }
      }
      this.isAllCheck.value = isAllCheck;
    });
  }

  @override
  Future<CartEntity?> loadData() async {
    final res = CartService.queryCart();
    return res;
  }

  //获取所有的需要操作的 ID
  List<int> getCheckedIds(bool check) {
    final list = data.value?.cartList ?? [];
    if (list.isEmpty) {
      return [];
    }
    final ids = list.where((element) => element.checked != check).map((e) => e.productId ?? 0).toList();
    return ids;
  }

  @override
  void addCart(int goodsId, int productId, int number) {
    refreshData();
  }

  @override
  void cartCheck(List<int> productId, bool isCheck) {
    refreshData();
  }

  @override
  void cartCheckOut(int cartId) {
    refreshData();
  }

  @override
  void deleteCart(List<int> productIds) {
    refreshData();
  }

  @override
  void updateCart(int productId, int goodsId, int number, int cartId) {
    refreshData();
  }
}
